﻿using System;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml.Serialization;
using MangaUtils;
using System.Collections.Generic;
using System.Windows.Forms;

namespace MangaReader
{
	/// <summary>
	/// Window with list of all added manga projects
	/// </summary>
	public partial class MangaManager
	{
		/// <summary>
		/// Manga reader to display.
		/// </summary>
		private Reader reader;
		/// <summary>
		/// Reader's current state. See MangaReaderState class description for details.
		/// </summary>
		private MangaReaderState state;

		/// <summary>
		/// Default constructor - loads previously added projects and fills listview with them.
		/// </summary>
		public MangaManager()
		{
			InitializeComponent();
			LoadChanges();			
			FillListViewWithManga();
		}

		/// <summary>
		/// Fills listview control with manga projects.
		/// </summary>
		private void FillListViewWithManga()
		{
			projectsListView.Items.Clear();
			int count = 0;
			foreach (var mangaItem in state.Projects)
			{
				var sp = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal };
				try
				{
					sp.Children.Add(new Image { Source = new BitmapImage(new Uri(mangaItem.CoverPath)) });
				}
				catch
				{
					sp.Children.Add(new Image());
				}
				sp.Children.Add(new TextBlock
				{
					Text = mangaItem.Title + (mangaItem.AuthorStudio != string.Empty ? " by " + mangaItem.AuthorStudio : "")
										   + " ["
										   + mangaItem.ProjectFolder.Subfolders.Count
										   + (mangaItem.ProjectFolder.Subfolders.Count == 1 ? " volume]" : " volumes]"),
					Foreground = Brushes.Black
				});
				sp.Tag = count;
				sp.Height = 60;
				projectsListView.Items.Add(sp);
				count++;
			}			
		}

		private void readButton_Click(object sender, RoutedEventArgs e)
		{
			if (projectsListView.SelectedItem == null)
			{
				System.Windows.MessageBox.Show("Please, select at least one manga!", "Empty selection", MessageBoxButton.OK, MessageBoxImage.Information);
				return;
			}
			var selIndex = ((StackPanel)projectsListView.SelectedItem).Tag as int?;
			if ((selIndex.HasValue) && (selIndex.Value >= 0))
			{
				reader = new Reader(state.Projects[selIndex.Value]);
				if (!reader.IsReady)
					return;
				Hide();
				reader.ShowDialog();
				Show();
				Focus();
			}
			else
				System.Windows.MessageBox.Show("Please, add at least one manga!", "Empty list", MessageBoxButton.OK, MessageBoxImage.Exclamation);
		}

		private void addFolderButton_Click(object sender, RoutedEventArgs e)
		{
			var dialog = new AddMangaWindow {Owner = this};
			dialog.ShowDialog();
			if (dialog.pathBox.Text != "")
			{
				var manga = new Manga(dialog.pathBox.Text, dialog.titleBox.Text, dialog.authorBox.Text, dialog.coverPath);
				state.Projects.Add(manga);
				FillListViewWithManga();
			}
		}

		/// <summary>
		/// Saves MangaReaderState into an XML file.
		/// </summary>
		private void SaveChanges()
		{
			try
			{
				var xw = System.Xml.XmlWriter.Create("projects.xml");
				var xs = new XmlSerializer(typeof(MangaReaderState));
				xs.Serialize(xw, state);
				xw.Close();
			}
			catch (Exception e)
			{
				System.Windows.MessageBox.Show(e.Message);
			}
		}

		/// <summary>
		/// Loads projects from XML file stored in MangaReader's main folder.
		/// Also checks all projects to be valid.
		/// </summary>
		private void LoadChanges()
		{
			try
			{
				var inputStream = System.Xml.XmlReader.Create("projects.xml");
				var xs = new XmlSerializer(typeof(MangaReaderState));
				state = xs.Deserialize(inputStream) as MangaReaderState;

				var newProjects = new List<Manga>();
				if (state != null)
				{
					foreach (var mangaProject in state.Projects)
					{
						try
						{
							//let's update existing projects — if there are any changes.
							mangaProject.ProjectFolder = new Folder(mangaProject.ProjectFolder.Path);
							newProjects.Add(mangaProject);
						}
						catch(Exception)
						{
							System.Windows.MessageBox.Show("An error occured during checking projects for existence. Please, check the following location and add project again:\r\n" +
							                String.Format("Title: {0}\r\nAuthor: {1}\r\nPath: {2}", mangaProject.Title, mangaProject.AuthorStudio, mangaProject.ProjectFolder.Path),
							                "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
						}
					}
					state.Projects = newProjects;
				}
				inputStream.Close();
			}
			catch (FileNotFoundException)
			{
				state = null;
			}
			finally
			{
				if (state == null)
					state = new MangaReaderState();
			}
		}

		private void Window_Closing(object sender, CancelEventArgs e)
		{
			SaveChanges();
		}

		private void readCustomButton_Click(object sender, RoutedEventArgs e)
		{
			var d = new FolderBrowserDialog();
			if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				string strCover = Directory.GetFiles(d.SelectedPath)[0];
				reader = new Reader(new Manga(d.SelectedPath, "Temp", "", strCover));
				if (!reader.IsReady)
					return;
				Hide();
				reader.ShowDialog();
				Show();
				Focus();
			}
		}
	}
}
